package yicheng.dinnertogetherapp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.amazonaws.HttpMethod;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


public class MeSettingActivity extends Activity {

	public static AmazonClientManager clientManager;

	public static SharedPreferences local_user_information;
	private SharedPreferences.Editor local_user_editor;
	private String PREFS_NAME = "LocalUserInfo";



	private Button log_out_button, my_nickname_setting_button, my_password_setting_button, my_photo_setting_button;

	private ImageButton my_photo_imageButton;




	private String PHONE_NUMBER, NICKNAME, ONLINE, PHOTO_PATH;

	private TextView my_nickname_setting_display_textView;


	private String defaultPhotoFilePath;

	private final String photoFileDirectory = android.os.Environment
			.getExternalStorageDirectory()
			+ File.separator
			+ "Eatogether" + File.separator + "myPhoto" + File.separator;


	int thumbNailPhotoWidth = 92;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.me_setting_layout);
		overridePendingTransition(R.anim.activity_left_in,R.anim.activity_left_out);

		log_out_button = (Button) findViewById(R.id.me_setting_logout_button);
		my_nickname_setting_button = (Button) findViewById(R.id.my_nickname_setting_button);
		my_password_setting_button = (Button) findViewById(R.id.my_password_setting_button);
		my_photo_setting_button = (Button) findViewById(R.id.my_photo_setting_button);
		my_photo_imageButton = (ImageButton) findViewById(R.id.my_photo_imageButton);


	/*	runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						File file = new File(photoFileDirectory,  "myPhoto.jpg");

						try {
							FileUtils.copyURLToFile(new URL("https://picture-bucket-akiaj2hg4ixizetrwc2a.s3-us-west-2.amazonaws.com/2060000001?AWSAccessKeyId=AKIAJ2HG4IXIZETRWC2A&Expires=1410421959&response-content-type=image%2Fjpeg&Signature=3hwiZ4xC8IDcMr3Pd4Q50ILvpQs%3D"), file);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();


						}

					}
					
				}).start();
			}
			
		});
		*/
		
		
		
		my_nickname_setting_display_textView = (TextView) findViewById(R.id.my_nickname_setting_display_textView);



		clientManager = new AmazonClientManager();

		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");
		my_nickname_setting_display_textView.setText(NICKNAME);


		updateDisplay();

		setLogOutButtonControl();
		setMyNicknameSettingButtonControl();
		setMyPasswordSettingButtonControl();
		setMyPhotoSettingButtonControl();


		setMyPhotoImageButtonControl();


	}



	private void updateDisplay(){
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		defaultPhotoFilePath = local_user_information.getString("defaultPhotoPath", "default");
		PHOTO_PATH = local_user_information.getString("PhotoPath", defaultPhotoFilePath);


		if (PHOTO_PATH.equals("default")){

			File folder = new File(photoFileDirectory);
			if (!folder.exists()) {
			    folder.mkdir();
			}
			
			Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.default_photo);

			File file = new File(photoFileDirectory,  "defaultPhoto.png");

			OutputStream fOut = null;

			try {
				fOut = new FileOutputStream(file);
				image.compress(Bitmap.CompressFormat.PNG, 85, fOut);
				fOut.flush();
				fOut.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			local_user_editor = local_user_information.edit();
			local_user_editor.putString("defaultPhotoPath", photoFileDirectory + "defaultPhoto.png");

			local_user_editor.commit();

			setImageButtonPhoto(photoFileDirectory + "defaultPhoto.png");

			defaultPhotoFilePath = local_user_information.getString("defaultPhotoPath", "default");

			uploadImageToS3();


		}
		else{
			/*		local_user_editor = local_user_information.edit();
						local_user_editor.remove("defaultPhotoPath");
						local_user_editor.remove("PhotoPath");
						local_user_editor.commit();*/

			setImageButtonPhoto(PHOTO_PATH);


		}


	}

	private final int REQUEST_CAMERA = 1;
	private final int SELECT_FILE = 2;



	private void setMyPhotoSettingButtonControl(){
		my_photo_setting_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(MeSettingActivity.this);
				builder.setTitle("Upload your image")
				.setItems(new CharSequence []{"Choose from gallery", "Take a photo", "Cancel"}, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0){
							Intent intent = new Intent(
									Intent.ACTION_PICK,
									android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
							intent.setType("image/*");
							startActivityForResult(
									Intent.createChooser(intent, "Select Image"),
									SELECT_FILE);

						}

						if (which == 1){
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());


							File f = new File(photoFileDirectory, timeStamp + ".jpg");
							intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
							startActivityForResult(intent, REQUEST_CAMERA);

							local_user_editor = local_user_information.edit();
							local_user_editor.putString("PhotoPath", photoFileDirectory + timeStamp + ".jpg");
							local_user_editor.commit();



							/*	Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
							Uri contentUri = Uri.fromFile(f);
							mediaScanIntent.setData(contentUri);
							sendBroadcast(mediaScanIntent);
							 */


						}

						if (which == 2){
							dialog.dismiss();
						}



					}



				}).create().show();;



			}
		});
	}



	private void uploadImageToS3(){
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials( PropertyLoader.getInstance().getAccessKey(), PropertyLoader.getInstance().getSecretKey() ) );      


						String currentPhotoPath = local_user_information.getString("PhotoPath", defaultPhotoFilePath);

						List<Bucket> listOfBucket = s3Client.listBuckets();

						String uploadedPhotoName = PHONE_NUMBER;


						PutObjectRequest por = new PutObjectRequest( listOfBucket.get(2).getName(), uploadedPhotoName, new java.io.File( currentPhotoPath) );  
						s3Client.putObject( por );


						/*	URL currentUrl = s3Client.getUrl(listOfBucket.get(2).getName(), uploadedPhotoName);

						if (currentUrl == null){*/

						ResponseHeaderOverrides override = new ResponseHeaderOverrides();
						override.setContentType( "image/jpeg" );


						GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest( listOfBucket.get(2).getName(), uploadedPhotoName);

						request.setResponseHeaders(override);
						request.setMethod(HttpMethod.GET); // Default.
						URL url = s3Client.generatePresignedUrl( request );


						SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.PHOTO_URL_ITEM, SimpleDB.PHOTO_URL_ATTRIBUTE, url.toString());



						Log.d("generated url", url.toString());

						//Toast.makeText(getBaseContext(), url.toString(), Toast.LENGTH_LONG).show();


						/*	}*/


					}

				}).start();
			}

		});



	}




	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_CAMERA) {


				String currentPhotoPath = local_user_information.getString("PhotoPath", defaultPhotoFilePath);
				setImageButtonPhoto(currentPhotoPath);

				uploadImageToS3();


			} else if (requestCode == SELECT_FILE) {

				Uri selectedImageUri = data.getData();

				String tempPath = getPath(selectedImageUri, MeSettingActivity.this);


				local_user_editor = local_user_information.edit();
				local_user_editor.putString("PhotoPath", tempPath);
				local_user_editor.commit();

				setImageButtonPhoto(tempPath);

				uploadImageToS3();

			}
		}


	}



	private void setImageButtonPhoto(String photoPath){




		//rotatedPhoto = Bitmap.createScaledBitmap(rotatedPhoto, 92, 92, true);

		my_photo_imageButton.setImageBitmap(decodeSampledBitmapFromUri(photoPath, thumbNailPhotoWidth, thumbNailPhotoWidth));



	}


	private Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
		Bitmap bm = null;

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);


		ExifInterface exif = null;
		try {
			exif = new ExifInterface(path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 

		int rotationInDegrees = exifToDegrees(rotation);

		Matrix matrix = new Matrix();
		if (rotation != 0f) {
			matrix.preRotate(rotationInDegrees);
		}

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		bm = BitmapFactory.decodeFile(path, options); 

		return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

		//return bm;  
	}

	private int exifToDegrees(int exifOrientation) {        
		if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } 
		else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {  return 180; } 
		else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {  return 270; }            
		return 0;    
	}


	private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float)height / (float)reqHeight);   
			} else {
				inSampleSize = Math.round((float)width / (float)reqWidth);   
			}   
		}

		return inSampleSize;   
	}

	private void setMyPhotoImageButtonControl(){
		my_photo_imageButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				defaultPhotoFilePath = local_user_information.getString("defaultPhotoPath", "default");
				String currentPhotoPath = local_user_information.getString("PhotoPath", defaultPhotoFilePath);

				Bundle dataBundle = new Bundle();
				dataBundle.putString("photoFilePath", currentPhotoPath);



				Intent goToShowMyPhotoActivityIntent = new Intent("yicheng.dinnertogetherapp.SHOWLARGEPHOTOACTIVITY");
				goToShowMyPhotoActivityIntent.putExtra("photoInfo", dataBundle);

				startActivity(goToShowMyPhotoActivityIntent);

			}
		});
	}


	private String getPath(Uri uri, Activity activity) {
		String[] projection = { MediaColumns.DATA };
		Cursor cursor = activity
				.managedQuery(uri, projection, null, null, null);
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}













	private void setLogOutButtonControl(){
		log_out_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				local_user_editor = local_user_information.edit();

				//clear local user data in shared preference
				//local_user_editor.putString("PhoneNumber", "default");
				local_user_editor.putString("Password", "default");
				local_user_editor.putBoolean("notRegistered", true);	

				local_user_editor.putString("Preference", "Preference");
				local_user_editor.putString("start_time", "0 : 00 AM");
				local_user_editor.putString("end_time", "0 : 00 PM");

				local_user_editor.remove("PhotoPath");



				local_user_editor.commit();

				//new loadDataBase().execute();
				Toast.makeText(MeSettingActivity.this,String.valueOf(local_user_information.getString("PhoneNumber", "phonenumber") ), Toast.LENGTH_SHORT).show();
				Toast.makeText(MeSettingActivity.this,String.valueOf(local_user_information.getString("Password", "password") ), Toast.LENGTH_SHORT).show();
				Toast.makeText(MeSettingActivity.this,String.valueOf(local_user_information.getBoolean("notRegistered", false) ), Toast.LENGTH_SHORT).show();


				/*MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, DateUpdateService.class));

				MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, BackgroundDateUpdateService.class));*/

				//if (!PHONE_NUMBER.equals(PRIMARY_PHONE_NUMBER)){
				//MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, UserInfoUpdateService.class));
				//}




				Intent gotoLogInViewIntent = new Intent("yicheng.dinnertogetherapp.LOGINACTIVITY");
				startActivity(gotoLogInViewIntent);

				finish();

			}
		});
	}


	private void setMyNicknameSettingButtonControl(){
		my_nickname_setting_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub



				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MeSettingActivity.this);				
				LayoutInflater factory = LayoutInflater.from(MeSettingActivity.this);
				View deleteDialogView = factory.inflate(
						R.layout.change_nickname_layout, null);



				dialogBuilder.setView(deleteDialogView);

				final EditText change_nickname_dialog_editText = (EditText) deleteDialogView.findViewById(R.id.change_nickname_dialog_editText);

				change_nickname_dialog_editText.setText(NICKNAME);
				int textLength = change_nickname_dialog_editText.getText().length();
				change_nickname_dialog_editText.setSelection(textLength, textLength);





				dialogBuilder.setCancelable(true);
				dialogBuilder.setTitle("Change Nickname");
				dialogBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(final DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						if (!change_nickname_dialog_editText.getText().toString().equals(NICKNAME)){
							if (isConnectedToInternet()){
								changeUserNickname(change_nickname_dialog_editText.getText().toString());

								local_user_editor = local_user_information.edit();
								local_user_editor.putString("Nickname", change_nickname_dialog_editText.getText().toString());
								local_user_editor.commit();

								NICKNAME = local_user_information.getString("Nickname", "default");
								my_nickname_setting_display_textView.setText(NICKNAME);

								updateFriendListMyNickname();


							}
							else{
								Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();

								dialog.cancel();

							}

						}

					}

				});

				dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						dialog.dismiss();



					}
				});

				AlertDialog dialog = dialogBuilder.create();
				dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
				dialog.show();


			}
		});
	}

	private void setMyPasswordSettingButtonControl(){
		my_password_setting_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MeSettingActivity.this);				
				LayoutInflater factory = LayoutInflater.from(MeSettingActivity.this);
				View deleteDialogView = factory.inflate(
						R.layout.change_password_layout, null);



				dialogBuilder.setView(deleteDialogView);
				final EditText change_password_dialog_editText = (EditText) deleteDialogView.findViewById(R.id.change_password_dialog_editText);
				final EditText change_password_second_dialog_editText = (EditText) deleteDialogView.findViewById(R.id.change_password_second_dialog_editText);



				dialogBuilder.setCancelable(true);
				dialogBuilder.setTitle("Change Password");
				dialogBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String currentPassword = local_user_information.getString("Password", "default");

						if (change_password_dialog_editText.getText().toString().equals(change_password_second_dialog_editText.getText().toString())){
							if (!change_password_dialog_editText.getText().toString().equals(currentPassword)){
								if (isConnectedToInternet()){

									changeUserPassword(change_password_dialog_editText.getText().toString());
									local_user_editor = local_user_information.edit();
									local_user_editor.putString("Password", change_password_dialog_editText.getText().toString());
									local_user_editor.commit();
									//updateDisplay();

								}
								else{
									Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
									dialog.cancel();
								}
							}
						}


					}

				});

				dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});

				AlertDialog dialog = dialogBuilder.create();
				dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
				dialog.show();
			}
		});
	}

	private void changeUserNickname(final String newNickname){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.NICKNAME_ITEM, SimpleDB.NICKNAME_ATTRIBUTE, newNickname);

					}

				}).start();
			}

		});
	}


	private void changeUserPassword(final String newPassword){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.PASSWORD_ITEM, SimpleDB.PASSWORD_ATTRIBUTE, newPassword);

					}

				}).start();
			}

		});

	}















	private boolean isConnectedToInternet(){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)MeSettingActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi_network = 
				connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobile_network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		//Only for testing
		return wifi_network.isConnectedOrConnecting() || mobile_network.isConnectedOrConnecting();
		/*return  mobile_network.isConnectedOrConnecting();*/
	}


	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}


	private void updateFriendListMyNickname(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");
		ONLINE = local_user_information.getString("online_offline", "default");
		local_user_editor = local_user_information.edit();

		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (ONLINE.equals("Online")){

							SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE, "online");

							HashMap<String,String> myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							myFriendList.remove("2060000000");
							myFriendList.remove("Name");

							String [] myFriendNumberList =  myFriendList.keySet().toArray(new String[0]);		

							HashMap<String, String> beUnavailableToFriendsList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);


							for (int i = 0; i < myFriendNumberList.length; i++){

								if (!beUnavailableToFriendsList.containsKey(myFriendNumberList[i])){
									HashMap<String, String> onlineFriendList = SimpleDB.getAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
									onlineFriendList.put(PHONE_NUMBER, NICKNAME);
									SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
									SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM, onlineFriendList);

									HashMap<String, String> offlineFriendList = SimpleDB.getAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
									offlineFriendList.remove(PHONE_NUMBER);
									SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
									SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM, offlineFriendList);
								}
							}

							myFriendList.put("2060000000", "dummyUser");

							SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM, myFriendList);


							/*		local_user_editor.putString("online", "online");
							local_user_editor.commit();*/

						}
						else{

							SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE, "offline");


							HashMap<String,String> myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							myFriendList.remove("2060000000");
							myFriendList.remove("Name");


							String [] myFriendNumberList =  myFriendList.keySet().toArray(new String[0]);		


							for (int i = 0; i < myFriendNumberList.length; i++){

								HashMap<String, String> onlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
								onlineFriendList.remove(PHONE_NUMBER);
								SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
								SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM, onlineFriendList);

								HashMap<String, String> offlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
								offlineFriendList.put(PHONE_NUMBER, NICKNAME);
								SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
								SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM, offlineFriendList);
							}

							myFriendList.put("2060000000", "dummyUser");


							SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM, myFriendList);

							/*	local_user_editor.putString("online", "offline");
							local_user_editor.commit();*/
						}







					}




				}).start();
			}

		});

	}



}
